import { asyncRoutes, constantRoutes } from '@/router'
import { getRouters } from '@/api/system/menu'
import Layout from '@/layout'// 【新加入】引入layout

// 获取访问路径
export function getPath(item) {
  if (item.menuPathSecond != null) {
    const url = item.menuPath + '/' + item.menuPathSecond
    console.log('url ------ ', url)
    return url
  } else {
    console.log('url ------ ', item.menuPath)
    return item.menuPath
  }
}

// 动态获取路由
export function generaMenu(routes, data) {
  // console.log('data ================ ', data)
  // data挨个遍历
  data.forEach(item => {
    // path不为空的话，就新建一个对象，装数据
    if (item.path !== '') {
      // console.log('动态获取路由 ----------- ', JSON.stringify(item))

      // 这个就仿照目录的机构，搭建
      const menu = {
        path: getPath(item),
        component: Layout, // 这个不用写data里面的内容，引用就行了
        // redirect: item.redirect,
        children: [],
        meta: { // 使用 title 和 icon 创建 meta 对象
          title: item.menuName,
          icon: item.menuIcon
        }
      }
      // 遍历子标签，并加入到主目录的children中去
      // 判断是否有子标签
      if (item.children && Array.isArray(item.children) && item.children.length > 0) {
        // 遍历子标签，并加入到主目录的 children 中去
        item.children.forEach(childItem => {
          const menu2 = {
            path: childItem.menuPath,
            component: (resolve) => require([`@/views${childItem.component}`], resolve),
            name: childItem.menuName,
            meta: { // 使用 title 和 icon 创建 meta 对象
              title: childItem.menuName,
              icon: childItem.menuIcon
            }
          }
          // 加入到主目录的 children 中去
          menu.children.push(menu2)
        })
      }
      // 追加
      routes.push(menu)
    }
  })
  // 把404加到最后，因为作者说  // 404 page must be placed at the end !!!
  const menu3 = {
    path: '*',
    redirect: '/404',
    hidden: true
  }
  // 追加
  routes.push(menu3)
}

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    console.log('route.meta.roles', route.meta.roles)
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes 所有路由
 * @param roles 当前角色
 */
export function filterAsyncRoutes(routes, roles) {
  console.log('routes信息 ===== ', routes)
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  console.log('处理结果 ', res)

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit, rootState }) {
    return new Promise(resolve => {
      const loadMenuData = [] // 保留加载动态路由的代码

      // getRouters 调用可能也需要根据你的需要来决定是否删除
      getRouters(rootState.user.token).then(response => {
        console.log('获取路由 ---------- ', response)
        // let data = response

        const data = response.data
        Object.assign(loadMenuData, data)
        const tempAsyncRoutes = Object.assign([], asyncRoutes)
        generaMenu(tempAsyncRoutes, loadMenuData)
        // let accessedRoutes
        const accessedRoutes = tempAsyncRoutes || []

        // console.log('动态路由信息 ', asyncRoutes)

        console.log('读取路由信息', accessedRoutes)
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      })
    }).catch(error => {
      console.log(error)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
